# -*- coding: utf-8 -*-
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Standard Imports
import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

class ContentHandler(webapp.RequestHandler):

  def render(self, data={}, template_path=None, status=None,
             message=None, relpath=None):
    if status is not None and status != 200:
      self.response.set_status(status, message)

      # Check if we have a customize error page (template) to display.
      if template_path is None:
        logging.error(message)
        self.response.set_status(status, message)
        self.response.out.write(message)
        return

    current = ''
    if relpath is not None:
      current = relpath.split('/')[0].split('.')[0]

    # Strip out language code from path. Urls changed for i18n work and correct
    # disqus comment thread won't load with the changed urls.
    path_no_lang = re.sub('^\/\w{2,3}\/', '', self.request.path, 1)
    logging.info(path_no_lang)

    pagename = ''
    if (path_no_lang == ''):
      pagename = 'home'
    else:
      pagename = re.sub('\/', '-', path_no_lang)
      pagename = re.sub('/$|-$', '', pagename)
      pagename = re.sub('^-', '', pagename)

    # Add template data to every request.
    template_data = {
      'toc': self.get_toc(template_path),
      'self_url': self.request.url,
      'self_pagename': pagename,
      'host': '%s://%s' % (self.request.scheme, self.request.host),
      'is_mobile': self.is_awesome_mobile_device(),
      'current': current,
      'prod': common.PROD,
      'sorted_profiles': models.get_sorted_profiles() # TODO: Don't add profile data on every request.
    }

    # If the tutorial contains a social URL override, use it.
    template_data['disqus_url'] = template_data['host'] + '/' + path_no_lang
    if data.get('tut') and data['tut'].social_url:
      template_data['disqus_url'] = template_data['host'] + data['tut'].social_url

    # Request was for an Atom feed. Render one!
    if self.request.path.endswith('.xml'):
      self.render_atom_feed(template_path, self.get_feed(template_path))
      return

    template_data.update(data)
    if not 'category' in template_data:
      template_data['category'] = _('this feature')

    # Add CORS support entire site.
    self.response.headers.add_header('Access-Control-Allow-Origin', '*')
    self.response.headers.add_header('X-UA-Compatible', 'IE=Edge,chrome=1')
    self.response.out.write(template.render(template_path, template_data))

  def _set_cache_param(self):
    # Render uncached verion of page with ?cache=1
    if self.request.get('cache', default_value='1') == '1':
      self.request.cache = True
    else:
      self.request.cache = False

  def get(self, relpath):

    self._set_cache_param()

    # Handle humans before locale, to prevent redirect to /en/
    # (but still ensure it's dynamic, ie we can't just redirect to a static url)
    if (relpath == 'humans.txt'):
      self.response.headers['Content-Type'] = 'text/plain'
      sorted_profiles = models.get_sorted_profiles()
      return self.render(data={'sorted_profiles': sorted_profiles,
                               'profile_amount': len(sorted_profiles)},
                         template_path='content/humans.txt',
                         relpath=relpath)
    else:
      self.render(status=404, message='Page Not Found',
                  template_path=os.path.join(os.path.dirname, 'index/index.html'))

def main():
  application = webapp.WSGIApplication([('/(.*)', ContentHandler)], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()
